#include "graph.h"
#include "cluster.h"

int main (int argc, const char * argv[])
{
    char inputFolder[CMD_LINE_MAX_SIZE], outputFolder[CMD_LINE_MAX_SIZE];
    int status=0;
    int kMax = 2, i;
    double objval, *x=NULL, *objvals=NULL;
    int nEdges, nVertices, LB, UB;
    char bound;
    
    
    argc = 5;
    argv[1] = "input/0";
    argv[2] = "output/0";
    argv[3] = "2";
    argv[4] = "3";
    
    
    
    /* arguments validation */
    if (argc != 5)
    {
    	fprintf (stderr, "Error: Only %d/5 arugments supplied\n", argc);
        return 1;
    }
    
    strcpy(inputFolder,argv[1]);
    strcpy(outputFolder,argv[2]);
    LB = atoi(argv[3]);
    UB = atoi(argv[4]);
    
    status = handleInput(inputFolder);
    if(status) {
        fprintf (stderr, "Error: failed to parse files\n");
        goto TERMINATE; 
    }
    
    
    nEdges = getNumEdges();
    nVertices = getNumVertices();
    
    objvals = (double*) calloc(UB-LB+1, sizeof(double));
    if (objvals == NULL)
    {
        fprintf (stderr, "Error: Memory allocation failed\n");
        status = 1;
        goto TERMINATE; 
    }
    
    for (kMax = LB, i=0; kMax<=UB; kMax++, i++)
    {
        status = k_cluster(kMax, &x, &objval);    
        if(status) {
            fprintf (stderr, "Error: Couldnt solve problem\n");
            goto TERMINATE; 
        }
        
        status = updateNetworkClusters(kMax, x);
        if(status) {
            fprintf (stderr, "Error: Couldnt update network\n");
            goto TERMINATE; 
        }
        
        bound = (kMax == LB) ? 'L' : 'K';
        
        status = buildXGMMLSolution(kMax, outputFolder, bound);
        if(status) {
            fprintf (stderr, "Error: Couldnt build xgmml files\n");
            goto TERMINATE; 
        }
        
        if (kMax == UB){
            
            status = buildXGMMLSolution(kMax, outputFolder, 'U');
            if(status) {
                fprintf (stderr, "Error: Couldnt build best cluster xgmml file\n");
                goto TERMINATE; 
            }
        }
        
        objvals[i] = objval;
        
        if (x != NULL){
            free(x); 
        }
        
    } 
    
    status = createResultsFile(strcat(outputFolder, "/results"), objvals, LB, UB);
    if(status) {
        fprintf (stderr, "Error: Couldnt create results file\n");
        goto TERMINATE; 
    }
    
TERMINATE:
    
    if (objvals != NULL)
    {
        free(objvals);
    }
    
    quitProperly();
    
    
    return 0;
}
